#!/usr/bin/env python
# coding: utf-8
import sys
import codecs

sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
import initlogging

import logging
import asyncio
from src.basedata.infrastructure.common.bootstrap import bootstrap
from src.config import CONF
from src.basedata.interfaces.facade.timer.regsiter_timer import register_timer_task
from src.basedata.common.dep_manage import ENVIRONMENT
from src.basedata.infrastructure.client.mongodb import init_mongo
from src.basedata.infrastructure.client.redis import init_redis
from src.basedata.infrastructure.common.unit_of_work import PersistenceUnitOfWorkFactory
from src.basedata.interfaces.facade.mq.rabitmq_consumer import rabbitmq_main
from src.basedata.interfaces.facade.api.asgi import init_web

logger = logging.getLogger(__name__)


def main():
    event_loop = asyncio.get_event_loop()

    mongo_client = init_mongo(CONF.mongodb)
    redis_client = init_redis(CONF.redis)

    uow_factory = PersistenceUnitOfWorkFactory(mongo_client=mongo_client, redis_client=redis_client)

    uow = uow_factory.uow()

    ENVIRONMENT.register_manual('uow', uow_factory.uow)

    bus = bootstrap(uow_factory=uow_factory.uow)

    rabbitmq_main(bus)
    # 注册定时任务
    event_loop.run_until_complete(register_timer_task(uow_factory.uow()))
    init_web(event_loop, CONF.api)
    logger.info('All modules started, running...')

    event_loop.run_forever()


if __name__ == '__main__':
    main()
